<template>
  <div class="market_cardactivity_card">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item">
            <span class="search-label">活动名称：</span>
            <Input placeholder="请输入" v-model="keywords" :maxlength="20"></Input>
          </Col>
          <Col class="search-item" style="display: flex; align-items: center">
            <span class="search-label">门店名称：</span>
            <vueTreeselectChoice
                :multiple="true"
                ref="vueTreeselectChoice"
                @input="handleShop"
                @on-api-finish="apiFinish"
                permissionCode="moms:market:cardactivityview"
                v-model="shopTypeShow"
              ></vueTreeselectChoice>
          </Col>
          <Col class="search-item">
            <span class="search-label">状态：</span>
            <Select v-model="status" style="width:180px" @on-change="search">
              <Option v-for="item in allStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="search"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end" class="search-item-right">
          <Col class="search-item"><Button class="search-btn" type="primary" @click="skipAdd" v-if="hasPermission('moms:market:cardactivitycreate')">新增</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe class="table-list" :loading="loading" :columns="columns" :data="data" :height="tableHeight">
      <template slot-scope="{ row }" slot="costRate">
        {{ row.costRate }}%
      </template>
      <template slot-scope="{ row }" slot="activityStatus">
        {{ getEnumsName(row.activityStatus, allStatus) }}
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys icondetail" title="查看详情" @click="skipDetail(row)" v-if="hasPermission('moms:market:cardactivitydetail')"></i>
        <i class="iconsys iconedit" @click="skipEdit(row)" title="编辑" v-if="hasPermission('moms:market:cardactivityupdate') && row.activityStatus !== 1"></i>
        <Poptip transfer confirm title="你确定要删除吗？" @on-ok="sureDel(row)" class="poptip_del" v-if="hasPermission('moms:market:cardactivitydelete') && row.activityStatus !== 1">
          <i class="iconsys icondel" title="删除"></i>
        </Poptip>
        <Poptip transfer confirm title="你确定要启用吗？" @on-ok="sureOpen(row)" class="poptip_del" v-if="hasPermission('moms:market:cardactivitystart') && row.activityStatus !== 1">
          <i class="iconsys iconshangjia" title="启用"></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import enumsMixin from './enums'
import { mapState } from 'vuex'
import { getCardLists, deleteCard, startCard } from '@/api/market/cardactivity/card.js'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'market_cardactivity_card',
  components: { vueTreeselectChoice },
  mixins: [enumsMixin],
  data () {
    return {
      keywords: '',
      shopTypeShow: [],
      shopType: [],
      shopList: [],
      status: -1,
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      data: [],
      columns: [
        {
          title: '活动名称',
          key: 'activityName'
        },
        {
          title: '门店',
          key: 'shopName'
        },
        {
          title: '活动成本率',
          slot: 'costRate'
        },
        {
          title: '活动总成本',
          key: 'costQty'
        },
        {
          title: '卡片盒数/盒',
          key: 'boxQty'
        },
        {
          title: '赠币总数量',
          key: 'coinQty'
        },
        {
          title: '状态',
          slot: 'activityStatus'
        }
      ]
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    })
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_cardactivity_card') {
        if (this.shopType && this.shopType.length) {
          this.getData()
        } else {
          this.$Message.error(`请选择门店列表`)
        }
      }
    }
  },
  mounted () {
    if (this.hasPermission(['moms:market:cardactivityupdate', 'moms:market:cardactivitydetail', 'moms:market:cardactivitydelete', 'moms:market:cardactivitystart'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 220
      })
    }
  },
  methods: {
    getData () {
      this.loading = true
      this.tableHeight = 0
      let params = {
        merchantId: this.merchantId,
        activityName: this.keywords,
        shopIds: this.shopType || [],
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }
      if (this.status !== -1) {
        params.activityStatus = this.status
      }
      getCardLists(params).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = result.data || []
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    skipDetail (row) {
      this.$router.push({
        name: 'market_cardactivity_card_detail',
        query: {
          id: row.activityCardId,
          shopId: row.shopId
        }
      })
    },
    skipEdit (row) {
      this.$router.push({
        name: 'market_cardactivity_card_edit',
        query: {
          id: row.activityCardId,
          shopId: row.shopId
        }
      })
    },
    sureDel (row) {
      deleteCard({
        merchantId: this.merchantId,
        shopId: row.shopId,
        activityCardId: row.activityCardId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          setTimeout(() => {
            this.getData()
          }, 300)
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    sureOpen (row) {
      startCard({
        merchantId: this.merchantId,
        shopId: row.shopId,
        activityCardId: row.activityCardId,
        operatorId: this.userId,
        operatorName: this.userName
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('启用成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    reset () {
      this.keywords = ''
      this.shopTypeShow = [this.$store.state.user.orgId]
      this.status = -1
      this.search()
    },
    search () {
      if (this.shopType && this.shopType.length) {
        this.pageIndex = 1
        this.getData()
      } else {
        this.$Message.error(`请选择门店列表`)
      }
    },
    skipAdd () {
      this.$router.push({ name: 'market_cardactivity_card_create' })
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.shopType = ids
      this.search()
    },
    apiFinish (isId) {
      if (isId) this.shopTypeShow = [this.$store.state.user.orgId]
    }
  }
}
</script>
